from apps.users.models import User
from rest_framework import serializers

class UserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'


from django.contrib.auth.models import Group
class GroupModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = Group
        fields = '__all__'


    def create(self, validated_data):

        # 这个方式，组和权限没有添加
        # user = User.objects.create_user(**validated_data)

        # 调用父类方法，完成数据保存
        user = super().create(validated_data)

        # 密码加密
        user.set_password(validated_data.get('password'))
        # 设置普通管理员
        user.is_staff=True

        user.save()

        return user


    def update(self, instance, validated_data):

        super().update(instance,validated_data)

        password = validated_data.get('password')

        if password is not None:
            instance.set_password(password)
            instance.save()

        return instance
